package com.gj.demojuc.chap07;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 线程间通信三种方式
 * 其中BlockingQueue阻塞队列适合消费者生产者的形式
 * 生产10个馒头 消费10个馒头，同一时刻最多生产3个馒头
 */
public class BlockingQueueDemo2 {
    public static void main(String[] args) {

        //创建阻塞队列
        BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(3);
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    System.out.println("开始生产馒头、、、");
                    Thread.sleep(2000);
                    blockingQueue.put(i);
                    System.out.println("生产了第" + i + "个馒头还剩" + blockingQueue.size() + "个馒头");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"生产者").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    System.out.println("开始消费馒头...");
                    Thread.sleep(3000);
                    Integer num = blockingQueue.take();
                    System.out.println("消费了第" + num + "个馒头剩余" + blockingQueue.size() + "个馒头");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"生产者").start();

    }

}
